public class BinarySearchTree {

    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val){
            this.val = val;
        }

    }

    public TreeNode root = null;

    public boolean search(int val){
        TreeNode cur = root;
        while (cur!=null){
            if (cur.val<val){
                cur = cur.right;
            }else if(cur.val>val){
                cur = cur.left;
            }else {
                return true;
            }
        }
        return false;

    }

    public boolean insert (int val){
        TreeNode node = new TreeNode(val);
        if (root==null){
            root=node;
            return true;
        }

        TreeNode cur = root;
        TreeNode p = cur;
        while (cur!=null){
            if (cur.val<val){
                p=cur;
                cur=cur.right;
            }else if (cur.val>val){
                p=cur;
                cur = cur.left;
            }else {
                return false;
            }
        }
        if (p.val<val){
            p.right = node;
        }else{
            p.left = node;
        }

        return true;

    }


    public void remove(int val){
        TreeNode cur = root;
        TreeNode p = cur;
        while (cur!=null){
            if (cur.val<val){
                p=cur;
                cur=cur.right;
            }else if (cur.val>val){
                p=cur;
                cur = cur.left;
            }else {
                removenode(p,cur);
                return;
            }
        }

    }

    private void removenode(TreeNode p, TreeNode cur) {
        if (cur.left==null){
            if (cur == root){
                root = cur.right;
            }else if(cur == p.left){
                p.left = cur.right;
            }else {
                p.right = cur.right;
            }

        }else if(cur.right == null){
            if (cur==root){
                root = cur.left;
            }else if(cur == p.left){
                p.left  = cur.left;
            }else {
                p.right = cur.right;
            }

        }else {
            TreeNode targetParent = cur;
            TreeNode target = cur.right;
            while (target.left!=null){
                 targetParent = target;
                 target = target.left;
            }
            cur.val = target.val;
            if (target == targetParent.left){
                targetParent.left = target.right;
            }else {
                targetParent.right = target.right;
            }

        }


    }


}
